package com.arthur.controller;

import com.arthur.bean.Order;
import com.arthur.bean.PageBean;
import com.arthur.bean.User;
import com.arthur.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AddOController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @RequestMapping("/AddOController")
    @ResponseBody
    protected Map orderInfo(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Map<String, Object> objectMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8");
        int orderid=Integer.parseInt(request.getParameter("orderid"));
        String pname=request.getParameter("pname");
        String uname=request.getParameter("uname");
        String isout=request.getParameter("isout");
        String riqi=request.getParameter("riqi");

        Order order=new Order();
        order.setOrderid(orderid);
        order.setPname(pname);
        order.setUname(uname);
        order.setIsout(isout);
        order.setRiqi(riqi);

        int count = userService.addOrderinfo(order);
        if (count==1){
            objectMap.put("result","1");
        }

        return objectMap;
    }

    @RequestMapping("/orderInfoListController")
    @ResponseBody
    protected Map orderInfoList(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Map<String, Object> objectMap = new HashMap<>();
        String username=request.getParameter("username");
        int pageno = 1;
        try {
            pageno = Integer.parseInt(request.getParameter("pageno"));

        } catch (Exception e) {
        }

        int totalRows = userService.obtainOrderinfoRows();
        int maxpage = totalRows % PageBean.ROWS_PERPAGE == 0 ? totalRows / PageBean.ROWS_PERPAGE
                : (totalRows / PageBean.ROWS_PERPAGE + 1);

        if (pageno < 1) {
            pageno = 1;
        }

        if (pageno > maxpage) {
            pageno = maxpage;
        }
        List<Order> orderinfoList = userService.fetchOrderinfoListBypageno(pageno,username);
        response.setCharacterEncoding("UTF-8");
        if (orderinfoList == null || orderinfoList.size() < 1) {
            objectMap.put("result","0");
        } else {
            objectMap.put("prePage", pageno - 1);
            objectMap.put("nextPage", pageno + 1);
            objectMap.put("maxPage", maxpage);
            objectMap.put("orderinfoList", orderinfoList);
        }
        return objectMap;
    }
}
